package com.yorkfeng.blemulti.Service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.yorkfeng.blemulti.Utils.Constants;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

@SuppressLint("NewApi")
public class BluetoothLeService extends Service {
    private final static String TAG = BluetoothLeService.class.getSimpleName();

    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private String mBluetoothDeviceAddress;
    private BluetoothGatt mBluetoothGattLeft, mBluetoothGattRight;

    private int mConnectionStateLeft = STATE_DISCONNECTED;
    private int mConnectionStateRight = STATE_DISCONNECTED;

    private static final int STATE_DISCONNECTED = 0;
    private static final int STATE_CONNECTING = 1;
    private static final int STATE_CONNECTED = 2;
    private static final int BLUETOOTH_UNCONNECT = 257;
    private static final int BLUETOOTH_INNER_ERROR = 133;

    public final static String ACTION_GATT_CONNECTED = "com.ore.comfortfurniture.service.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED = "com.ore.comfortfurniture.service.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.ore.comfortfurniture.service.ACTION_GATT_SERVICES_DISCOVERED";
    public final static String ACTION_DATA_AVAILABLE = "com.ore.comfortfurniture.service.ACTION_DATA_AVAILABLE";
    public final static String ACTION_GATT_UNCONNECTED = "com.ore.comfortfurniture.service.ACTION_GATT_UNCONNECTED";
    // public final static String ACTION_GATT_INIT_SUCCESS =
    // "com.ore.bluehome.service.ACTION_GATT_INIT_SUCCESS";
    // public final static String ACTION_GATT_INIT_FAILURE =
    // "com.ore.bluehome.service.ACTION_GATT_INIT_FAILURE";
    public final static String EXTRA_DATA = "com.ore.comfortfurniture.service.EXTRA_DATA";

    // 加入队列，防止在前一条没写成功的时候就继续写
    // todo 断开连接之后清空
    private Queue<BluetoothGattCharacteristic> characteristicWriteQueueL = new LinkedList<BluetoothGattCharacteristic>();
    private Queue<BluetoothGattCharacteristic> characteristicReadQueueL = new LinkedList<BluetoothGattCharacteristic>();
    private Queue<BluetoothGattCharacteristic> characteristicWriteQueueR = new LinkedList<BluetoothGattCharacteristic>();
    private Queue<BluetoothGattCharacteristic> characteristicReadQueueR = new LinkedList<BluetoothGattCharacteristic>();

    public boolean isDiscoveryingL, isDiscoveryingR;

    // Implements callback methods for GATT events that the app cares about. For
    // example,
    // connection change and services discovered.
    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            String intentAction;
            Log.d(TAG, "=======status:" + status);
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                if (gatt.equals(mBluetoothGattLeft)) {
                    intentAction = ACTION_GATT_CONNECTED;
                    setmConnectionState(STATE_CONNECTED, 0);
                    broadcastUpdate(intentAction, 0);
                    // 正在发现服务中
                    isDiscoveryingL = true;
                }else {
                    intentAction = ACTION_GATT_CONNECTED;
                    setmConnectionState(STATE_CONNECTED, 1);
                    broadcastUpdate(intentAction, 1);
                    // 正在发现服务中
                    isDiscoveryingR = true;
                }

                Log.d(TAG, "Connected to GATT server.");
                // Attempts to discover services after successful connection.
                Log.d(TAG, "Attempting to start service discovery:" + gatt.discoverServices());

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                if (gatt.equals(mBluetoothGattLeft)) {
                    intentAction = ACTION_GATT_DISCONNECTED;
                    setmConnectionState(STATE_DISCONNECTED, 0);
                    Log.i(TAG, "Disconnected from GATT server.");
                    broadcastUpdate(intentAction, 0);
                    // 清空队列
                    characteristicWriteQueueL.clear();
                    characteristicReadQueueL.clear();
                    // 发现服务标志位
                    isDiscoveryingL = false;
                }else {
                    intentAction = ACTION_GATT_DISCONNECTED;
                    setmConnectionState(STATE_DISCONNECTED, 1);
                    Log.i(TAG, "Disconnected from GATT server.");
                    broadcastUpdate(intentAction, 1);
                    // 清空队列
                    characteristicWriteQueueR.clear();
                    characteristicReadQueueR.clear();
                    // 发现服务标志位
                    isDiscoveryingR = false;
                }
            }
            // status = 133
            // 257 蓝牙连接不上，重新连接
            if (status == BLUETOOTH_UNCONNECT || status == BLUETOOTH_INNER_ERROR) {
                Log.i(TAG, "蓝牙无法连接");

                intentAction = ACTION_GATT_UNCONNECTED;

                if (gatt.equals(mBluetoothGattLeft)) {
                    broadcastUpdate(intentAction, 0);
                }else {
                    broadcastUpdate(intentAction, 1);
                }
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                if (gatt.equals(mBluetoothGattLeft)) {
                    broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED, 0);
                    isDiscoveryingL = false;
                }else {
                    broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED, 1);
                    isDiscoveryingR = false;
                }

            } else {
                // 129 内部错误
                Log.w(TAG, "onServicesDiscovered received: " + status);

                if (status == 129) {
                    Log.i(TAG, "蓝牙无法发现服务");
                    String intentAction = ACTION_GATT_UNCONNECTED;
                    if (gatt.equals(mBluetoothGattLeft)) {
                        broadcastUpdate(intentAction, 0);
                    }else {
                        broadcastUpdate(intentAction, 1);
                    }
                }
            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            Log.d(TAG, "onCharacteristicRead");

            if (gatt.equals(mBluetoothGattLeft)) {
                characteristicReadQueueL.remove();

                if (status == BluetoothGatt.GATT_SUCCESS) {
                    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic, 0);
                }

                if (characteristicReadQueueL.size() > 0) {
                    mBluetoothGattLeft.readCharacteristic(characteristicReadQueueL.element());
                }
            }else {
                characteristicReadQueueR.remove();

                if (status == BluetoothGatt.GATT_SUCCESS) {
                    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic, 1);
                }

                if (characteristicReadQueueR.size() > 0) {
                    mBluetoothGattRight.readCharacteristic(characteristicReadQueueR.element());
                }
            }
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {

            Log.d(TAG, "onDescriptorWriteonDescriptorWrite = " + status + ", descriptor ="
                    + descriptor.getUuid().toString());
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            if (gatt.equals(mBluetoothGattLeft)) {
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic, 0);
            }else {
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic, 1);
            }
            // if (characteristic.getValue() != null)
            // {
            // Log.d(TAG, "onCharacteristicChanged" +
            // characteristic.getStringValue(0));
            // }
            Log.d(TAG, "--------onCharacteristicChanged-----");
        }

        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
            Log.d(TAG, "rssi = " + rssi);
        }

        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            Log.d(TAG, "--------write success----- status:" + status);
            // pop the item that we just finishing writing
            if (gatt.equals(mBluetoothGattLeft)) {
                characteristicWriteQueueL.remove();
                // if there is more to write, do it!
                if (characteristicWriteQueueL.size() > 0) {
                    Log.w(TAG, "阻塞");
                    // 写头元素
                    mBluetoothGattLeft.writeCharacteristic(characteristicWriteQueueL.element());
                }
                else if (characteristicReadQueueL.size() > 0) {
                    mBluetoothGattLeft.readCharacteristic(characteristicReadQueueL.element());
                }
            }else {
                characteristicWriteQueueR.remove();
                // if there is more to write, do it!
                if (characteristicWriteQueueR.size() > 0) {
                    Log.w(TAG, "阻塞");
                    // 写头元素
                    mBluetoothGattRight.writeCharacteristic(characteristicWriteQueueR.element());
                }
                else if (characteristicReadQueueR.size() > 0) {
                    mBluetoothGattRight.readCharacteristic(characteristicReadQueueR.element());
                }
            }
        };
    };

    private void broadcastUpdate(final String action, int gatt) {
        final Intent intent = new Intent(action);
        intent.putExtra("GATT", gatt);
        sendBroadcast(intent);
    }

    private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic, int gatt) {
        final byte[] data = characteristic.getValue();

        String uuid = characteristic.getUuid().toString();

        if (data != null && data.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for (byte byteChar : data) {
                stringBuilder.append(String.format("%02X ", byteChar));
            }

            Log.d(TAG, uuid + ":" + stringBuilder.toString());

            if (uuid.equals(Constants.UUID_READ_CHARACTERISTIC)) {
                Intent actionIntent = new Intent(ACTION_DATA_AVAILABLE);
                // byte 数组
                actionIntent.putExtra(EXTRA_DATA, data);
                actionIntent.putExtra("GATT", gatt);
                sendBroadcast(actionIntent);
            }
        }
    }

    public class LocalBinder extends Binder {
        public BluetoothLeService getService() {
            return BluetoothLeService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Service onCreate");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Service onDestroy");
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "Service onUnbind");
        Log.d(TAG, "service 解除绑定");
        // After using a given device, you should make sure that
        // BluetoothGatt.close() is called
        // such that resources are cleaned up properly. In this particular
        // example, close() is
        // invoked when the UI is disconnected from the Service.
        close();
        return super.onUnbind(intent);
    }

    private final IBinder mBinder = new LocalBinder();

    /**
     * Initializes a reference to the local Bluetooth adapter.
     *
     * @return Return true if the initialization is successful.
     */
    public boolean initialize() {
        // For API level 18 and above, get a reference to BluetoothAdapter
        // through
        // BluetoothManager.
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            if (mBluetoothManager == null) {
                Log.e(TAG, "Unable to initialize BluetoothManager.");
                return false;
            }
        }

        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
            return false;
        }

        return true;
    }

    /**
     * Connects to the GATT server hosted on the Bluetooth LE device.
     *
     * @param address
     *            The device address of the destination device.
     *
     * @return Return true if the connection is initiated successfully. The
     *         connection result is reported asynchronously through the
     *         {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
     *         callback.
     */
    public boolean connect(final String address, int gatt) {
        if (mBluetoothAdapter == null || address == null) {
            Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
            return false;
        }

        if (gatt == 0) {
            // 重新开始新的连接前，必须关掉之前的
            if (mBluetoothGattLeft != null) {
                close();
            }

            final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
            if (device == null) {
                Log.w(TAG, "Device not found.  Unable to connect.");
                return false;
            }
            // We want to directly connect to the device, so we are setting the
            // autoConnect
            // parameter to false.
            mBluetoothGattLeft = device.connectGatt(this, false, mGattCallback);
            Log.d(TAG, "Trying to create a new connection.");
            setmBluetoothDeviceAddress(address);
            setmConnectionState(STATE_CONNECTING, 0);

        }else if (gatt == 1) {
            // 重新开始新的连接前，必须关掉之前的
            if (mBluetoothGattRight != null) {
                close();
            }

            final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
            if (device == null) {
                Log.w(TAG, "Device not found.  Unable to connect.");
                return false;
            }
            // We want to directly connect to the device, so we are setting the
            // autoConnect
            // parameter to false.
            mBluetoothGattRight = device.connectGatt(this, false, mGattCallback);
            Log.d(TAG, "Trying to create a new connection.");
            setmBluetoothDeviceAddress(address);
            setmConnectionState(STATE_CONNECTING, 1);

        }

        return true;
    }

    /**
     * Disconnects an existing connection or cancel a pending connection. The
     * disconnection result is reported asynchronously through the
     * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
     * callback.
     */
    public void disconnect(int gatt) {

        if (gatt == 0) {
            if (mBluetoothAdapter == null || mBluetoothGattLeft == null) {
                Log.w(TAG, "BluetoothAdapter not initialized");
                return;
            }
            mBluetoothGattLeft.disconnect();
        }else if (gatt == 1) {
            if (mBluetoothAdapter == null || mBluetoothGattRight == null) {
                Log.w(TAG, "BluetoothAdapter not initialized");
                return;
            }
            mBluetoothGattRight.disconnect();
        }
    }

    /**
     * After using a given BLE device, the app must call this method to ensure
     * resources are released properly.
     */
    public void close() {
        if (mBluetoothGattLeft != null) {
            mBluetoothGattLeft.close();
            mBluetoothGattLeft = null;
        }
        if (mBluetoothGattRight != null) {
            mBluetoothGattRight.close();
            mBluetoothGattRight = null;
        }
    }

    public void wirteCharacteristic(BluetoothGattCharacteristic characteristic, int gatt) {

        if (gatt == 0) {
            if (mBluetoothAdapter == null || mBluetoothGattLeft == null) {
                Log.w(TAG, "BluetoothAdapter not initialized");
                return;
            }

            characteristicWriteQueueL.add(characteristic);
            if (characteristicWriteQueueL.size() == 1) {
                mBluetoothGattLeft.writeCharacteristic(characteristic);
            }
            // 写队列缓存的信息超过10条，断开蓝牙连接
            if (characteristicWriteQueueL.size() > 10) {
                // 重新连接之后需要清空
                Log.w(TAG, "读缓存的超过10条");
                disconnect(0);
            }
        }else if (gatt == 1) {
            if (mBluetoothAdapter == null || mBluetoothGattRight == null) {
                Log.w(TAG, "BluetoothAdapter not initialized");
                return;
            }

            characteristicWriteQueueR.add(characteristic);
            if (characteristicWriteQueueR.size() == 1) {
                mBluetoothGattRight.writeCharacteristic(characteristic);
            }
            // 写队列缓存的信息超过10条，断开蓝牙连接
            if (characteristicWriteQueueR.size() > 10) {
                // 重新连接之后需要清空
                Log.w(TAG, "读缓存的超过10条");
                disconnect(1);
            }
        }
    }

    /**
     * Request a read on a given {@code BluetoothGattCharacteristic}. The read
     * result is reported asynchronously through the
     * {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
     * callback.
     *
     * @param characteristic
     *            The characteristic to read from.
     */
    public void readCharacteristic(BluetoothGattCharacteristic characteristic, int gatt) {
        if (gatt == 0) {
            if (mBluetoothAdapter == null || mBluetoothGattLeft == null) {
                Log.w(TAG, "BluetoothAdapter not initialized");
                return;
            }
            // put the characteristic into the read queue
            characteristicReadQueueL.add(characteristic);
            // if there is only 1 item in the queue, then read it. If more than 1,
            // we handle asynchronously in the callback above
            // GIVE PRECEDENCE to descriptor writes. They must all finish first.
            if ((characteristicReadQueueL.size() == 1) && (characteristicWriteQueueL.size() == 0)) {
                mBluetoothGattLeft.readCharacteristic(characteristic);
            }
        }else if (gatt == 1) {
            if (mBluetoothAdapter == null || mBluetoothGattRight == null) {
                Log.w(TAG, "BluetoothAdapter not initialized");
                return;
            }
            // put the characteristic into the read queue
            characteristicReadQueueR.add(characteristic);
            // if there is only 1 item in the queue, then read it. If more than 1,
            // we handle asynchronously in the callback above
            // GIVE PRECEDENCE to descriptor writes. They must all finish first.
            if ((characteristicReadQueueR.size() == 1) && (characteristicWriteQueueR.size() == 0)) {
                mBluetoothGattRight.readCharacteristic(characteristic);
            }
        }
    }

    /**
     * Enables or disables notification on a give characteristic.
     *
     * @param characteristic
     *            Characteristic to act on.
     * @param enabled
     *            If true, enable notification. False otherwise.
     */
    public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled, int gatt) {
        if (gatt == 0) {
            if (mBluetoothAdapter == null || mBluetoothGattLeft == null) {
                Log.w(TAG, "BluetoothAdapter not initialized");
                return;
            }

            boolean isEnableNotification = mBluetoothGattLeft.setCharacteristicNotification(characteristic, true);
            if(isEnableNotification) {
                List<BluetoothGattDescriptor> descriptorList = characteristic.getDescriptors();
                if(descriptorList != null && descriptorList.size() > 0) {
                    for(BluetoothGattDescriptor descriptor : descriptorList) {
                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                        mBluetoothGattLeft.writeDescriptor(descriptor);
                    }
                }
            }
        }else if (gatt == 1) {
            if (mBluetoothAdapter == null || mBluetoothGattRight == null) {
                Log.w(TAG, "BluetoothAdapter not initialized");
                return;
            }

            boolean isEnableNotification = mBluetoothGattRight.setCharacteristicNotification(characteristic, true);
            if(isEnableNotification) {
                List<BluetoothGattDescriptor> descriptorList = characteristic.getDescriptors();
                if(descriptorList != null && descriptorList.size() > 0) {
                    for(BluetoothGattDescriptor descriptor : descriptorList) {
                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                        mBluetoothGattRight.writeDescriptor(descriptor);
                    }
                }
            }
        }
    }

    /**
     * Retrieves a list of supported GATT services on the connected device. This
     * should be invoked only after {@code BluetoothGatt#discoverServices()}
     * completes successfully.
     *
     * @return A {@code List} of supported services.
     */
    public List<BluetoothGattService> getSupportedGattServices(int gatt) {
        if (gatt == 0) {
            if (mBluetoothGattLeft == null)
                return null;

            return mBluetoothGattLeft.getServices();
        }else if (gatt == 1) {
            if (mBluetoothGattRight == null)
                return null;

            return mBluetoothGattRight.getServices();
        }
        return null;
    }

    /**
     * Read the RSSI for a connected remote device.
     * */
    public boolean getRssiVal(int gatt) {
        if (gatt == 0) {
            if (mBluetoothGattLeft == null)
                return false;

            return mBluetoothGattLeft.readRemoteRssi();
        }else if (gatt == 1) {
            if (mBluetoothGattRight == null)
                return false;

            return mBluetoothGattRight.readRemoteRssi();
        }
        return false;
    }

    public int getmConnectionState(int gatt) {
        if (gatt == 0) {
            return mConnectionStateLeft;
        }else if (gatt == 1) {
            return mConnectionStateRight;
        }
        return 100;
    }

    public void setmConnectionState(int mConnectionState, int gatt) {
        if (gatt == 0) {
            this.mConnectionStateLeft = mConnectionState;
        }else if (gatt == 1) {
            this.mConnectionStateRight = mConnectionState;
        }
    }

    public String getmBluetoothDeviceAddress() {
        return mBluetoothDeviceAddress;
    }

    public void setmBluetoothDeviceAddress(String mBluetoothDeviceAddress) {
        this.mBluetoothDeviceAddress = mBluetoothDeviceAddress;
    }

    public BluetoothGatt getmBluetoothGatt(int gatt) {
        if (gatt == 0) {
            return mBluetoothGattLeft;
        }else if (gatt == 1) {
            return mBluetoothGattRight;
        }
        return null;
    }

    public void setmBluetoothGatt(BluetoothGatt mBluetoothGatt, int gatt) {
        if (gatt == 0) {
            this.mBluetoothGattLeft = mBluetoothGatt;
        }else if (gatt == 1) {
            this.mBluetoothGattRight = mBluetoothGatt;
        }
    }
}
